<!DOCTYPE html>
<html>

<head>
    <title>方块移动</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body {
            font-family: Arial;
            text-align: center;
            padding: 20px;
        }

        .controls {
            margin: 20px auto;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 10px;
            width: 300px;
        }

        .grid {
            display: inline-block;
            border: 2px solid #333;
            background: #eee;
            margin-bottom: 20px;
        }

        .row {
            display: flex;
        }

        .cell {
            width: 80px;
            height: 80px;
            border: 1px solid #999;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
            background: white;
            transition: all 0.3s;
        }

        .cell.empty {
            background: #ddd;
            cursor: default;
        }

        .cell.movable {
            background: #ffff99;
        }

        .message {
            margin: 10px auto;
            padding: 10px;
            border-radius: 5px;
            width: 300px;
        }

        .error {
            background: #ffdddd;
            color: #d32f2f;
        }

        .success {
            background: #ddffdd;
            color: #388e3c;
        }

        .history {
            margin: 20px auto;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 10px;
            width: 300px;
        }
    </style>
</head>

<body>
    <h1>方块移动</h1>

    <div class="controls">
        <label>行数(N)：
            <select id="rows">
                <option value="3">3</option>
                <option value="5">5</option>
                <option value="7">7</option>
            </select>
        </label>

        <label>列数(M)：
            <select id="cols">
                <option value="3">3</option>
                <option value="5">5</option>
                <option value="7">7</option>
            </select>
        </label>

        <button id="generate">生成网格</button>
    </div>

    <div id="grid" class="grid"></div>

    <div id="message" class="message" style="display:none;"></div>

    <div class="history">
        <div>最近移动路径：</div>
        <div id="path"></div>
    </div>

    <script>
        $(function () {
            let grid = [], emptyPos = {}, path = [], last5Pos = [];

            // 生成网格
            $('#generate').click(function () {
                const rows = parseInt($('#rows').val());
                const cols = parseInt($('#cols').val());
                const centerRow = Math.floor(rows / 2), centerCol = Math.floor(cols / 2);

                // 初始化网格
                grid = [];
                let num = 1;
                for (let i = 0; i < rows; i++) {
                    grid[i] = [];
                    for (let j = 0; j < cols; j++) {
                        grid[i][j] = (i === centerRow && j === centerCol) ? 0 : num++;
                    }
                }

                emptyPos = { row: centerRow, col: centerCol };
                path = [`(${centerRow + 1},${centerCol + 1})`];
                last5Pos = [`${centerRow},${centerCol}`];
                updateGrid();
                $('#path').text(path[0]);
            });

            // 更新网格显示
            function updateGrid() {
                $('#grid').empty();
                for (let i = 0; i < grid.length; i++) {
                    const $row = $('<div class="row"></div>');
                    for (let j = 0; j < grid[i].length; j++) {
                        const $cell = $('<div class="cell"></div>')
                            .text(grid[i][j] || '0')
                            .data('pos', { row: i, col: j });

                        if (grid[i][j] === 0) $cell.addClass('empty');
                        else if (canMove(i, j)) $cell.addClass('movable');

                        $cell.click(moveCell);
                        $row.append($cell);
                    }
                    $('#grid').append($row);
                }
            }

            // 检查是否可以移动
            function canMove(row, col) {
                const dr = Math.abs(row - emptyPos.row);
                const dc = Math.abs(col - emptyPos.col);
                return (dr === 1 && dc === 0) || (dr === 0 && dc === 1);
            }

            // 移动方块
            function moveCell() {
                const pos = $(this).data('pos');
                const posStr = `${pos.row},${pos.col}`;

                // 检查是否最近5步已经到过这个位置
                if (last5Pos.includes(posStr)) {
                    showMsg("5步之内的移动不能重复!", "error");
                    return;
                }

                // 执行移动
                $(this).addClass('moving');
                setTimeout(() => {
                    // 更新网格数据
                    grid[emptyPos.row][emptyPos.col] = grid[pos.row][pos.col];
                    grid[pos.row][pos.col] = 0;

                    // 记录移动路径
                    path.push(`(${pos.row + 1},${pos.col + 1})`);
                    last5Pos.unshift(posStr);
                    if (last5Pos.length > 5) last5Pos.pop();

                    // 更新空白格位置
                    emptyPos = { row: pos.row, col: pos.col };

                    // 更新显示
                    updateGrid();
                    updatePath();
                    showMsg("移动成功！", "success");
                }, 200);
            }

            // 更新路径显示
            function updatePath() {
                let displayPath = path.slice(Math.max(0, path.length - 6));
                // if (path.length > 7) displayPath[0] = "...";
                $('#path').text(displayPath.join("→"));
            }

            // 显示消息
            function showMsg(text, type) {
                $('#message').text(text).removeClass().addClass('message ' + type).show();
                setTimeout(() => $('#message').hide(), 2000);
            }

            // 初始化
            $('#generate').click();
        });
    </script>
</body>

</html>